import React, { Component } from 'react'
import PubSub from 'pubsub-js';
// import PropTypes from "prop-types";
// import axios from "axios";
import './index.css'


export default class Search extends Component {

  // static propTypes = {
  //   updateAppState: PropTypes.func.isRequired
  // }

  search = async () => {
    const {inputKey:{value:inputKey}} = this
    // 更新list的状态
    PubSub.publish('updateUsers',{isFirst: false,isLoading: true})
    // 使用axios发送 xhr请求
    // axios.get(`https://api.github.com/search/users?q=${inputKey}`).then(res => {
    //   PubSub.publish('updateUsers',{isLoading: false, userList: res.data.items})
    // }).catch(err => PubSub.publish('updateUsers',{err: err.message}))

    // 使用fetch发送请求
    //#region 
    // fetch(`https://api.github.com/search/users?q=${inputKey}`).then(response => {
    //   // 第一步联系服务器   返回的也是一个promise   json()里边是成功的数据是一个promise
    //   console.log('联系服务器成功了', response); 
    //   return response.json()
    // }).then(result => {
    //   console.log(result);
    // }).catch(error => console.log('请求错误', error))
    //#endregion
    
    // 使用async await try catch 优化fetch请求
    try {
      const response = await fetch(`https://api.github.com/search/users?q=${inputKey}`)
      const result = await response.json()
      PubSub.publish('updateUsers',{isLoading: false, userList: result.items})
    } catch (error) {
      PubSub.publish('updateUsers',{err: error.message})
    }
    
  }
  render() {
    return (
      <div className='search'>
        <h2>搜索github用户</h2>
        <input type="text" ref={e => this.inputKey = e}/>
        <button onClick={this.search}>搜索</button>
      </div>
    )
  }
}
